package com.android.RssReader.Utils;

import java.io.InputStream;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.URL;

import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageView;

import com.android.RssReader.RssReaderApplication;

public class AsyncImageLoader {

	public AsyncImageLoader() {
		
	}

	public Drawable loadDrawable(final String imageUrl,
			final ImageView imageView, final ImageCallback imageCallback) {
		if (RssReaderApplication.getInstance().getImageCache().containsKey(imageUrl)) {
			SoftReference<Drawable> softReference = RssReaderApplication.getInstance().getImageCache().get(imageUrl);
			Drawable drawable = softReference.get();
			if (drawable != null) {
				return drawable;
			}
		} 
	
		final Handler handler = new Handler() {
			@Override
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, imageView,
						imageUrl);
			}
		};
		new Thread() {
			@Override
			public void run() {
				 Drawable drawable = null;
					try {
						drawable = Drawable.createFromStream(getRequest(imageUrl), null);
					} catch (Exception e) {
						e.printStackTrace();
					}
				RssReaderApplication.getInstance().getImageCache().put(imageUrl, new SoftReference<Drawable>(drawable));
				Message message = handler.obtainMessage(0, drawable);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	public interface ImageCallback {
		public void imageLoaded(Drawable imageDrawable, ImageView imageView,
				String imageUrl);
	}
	
	public  InputStream getRequest(String path) throws Exception {
		URL url = new URL(path);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if (conn.getResponseCode() == 200){
			return conn.getInputStream();
		}
		return null;
	}
}